/**
 * 合并分支表单
 */

import React from 'react';
import {
  Form,
  Input,
  Button,
  Field,
  Dropdown,
  Menu,
  Dialog,
  Balloon,
  Tag,
  Checkbox,
} from '@teamix/ui';
import intl from '../../../../../../../../../locale';

const { Tooltip } = Balloon;

const mrDataSource = [
  {
    key: 'no-fast-forward',
    title: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.CreateAMergeNode',
      defaultMessage: '创建一个合并节点',
    }),
    desc: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.AlwaysCreateAMergeNode',
      defaultMessage: '总是创建一个合并节点，记录合并信息',
    }),
  },

  {
    key: 'squash',
    title: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.SquashMerge',
      defaultMessage: 'Squash 合并',
    }),
    desc: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.MergeAndCompressOneOr',
      defaultMessage: '将一个或多个提交合并压缩合并为目标分支上的一个提交',
    }),
  },

  {
    key: 'rebase',
    title: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.RebaseMerge',
      defaultMessage: 'Rebase 合并',
    }),
    desc: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.EditReviewBranchSubmissionTo',
      defaultMessage: '将评审分支提交逐一编辑到目标分支',
    }),
  },

  {
    key: 'ff-only',
    title: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.FastForwardOnlyMerge',
      defaultMessage: 'Fast-forward-only 合并',
    }),
    desc: intl.get({
      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.UseFastForwardOnlyTo',
      defaultMessage: '使用 fast-forward-only 方式合并，不创建合并节点',
    }),
  },
];

export default class DoMergeAndDialog extends React.Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      visible: false,
      dropdownVisible: false,
      isCommitMsgInputVisible: true,
      merge_type: '',
    };
  }

  commitMessage = (key) => {
    const { codeReviewDetail, commitHistory } = this.props;

    const { title, description } = codeReviewDetail;
    let merge_commit_message_content;
    const location = window.location.origin + window.location.pathname;
    switch (key) {
      case 'no-fast-forward':
        merge_commit_message_content = `${title}

${location}  ${description ? `\n\n${description}` : ''}`;
        break;
      case 'squash': {
        const commitHistoryMessage =
          commitHistory && commitHistory.map((commit) => `* ${commit.message}`).join('\n\n');
        merge_commit_message_content = `${title}

${location}  ${description ? `\n\n${description}` : ''}

squash 合并:

${commitHistoryMessage}`;
        break;
      }
      case 'ff-only':
      case 'rebase':
        // rebase和fast-forward-only类型无需commit msg字段
        merge_commit_message_content = '';
        break;
      default:
    }

    // rebase和fast-forward-only类型无需commit msg字段
    this.setState({
      // isCommitMsgInputVisible: (key !== 'rebase' && key !== 'ff-only'),
      merge_type: key,
    });

    this.field.setValues({
      merge_commit_message_content,
    });
  };

  onOpen = (value) => {
    this.setState({
      visible: true,
    });

    this.commitMessage(value);
  };

  onDropdownClick = () => {
    const { dropdownVisible } = this.state;
    this.setState({
      dropdownVisible: !dropdownVisible,
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  onFormSave = () => {
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        const merge_commit_message = `${formData.merge_commit_message_title}\n\n${formData.merge_commit_message_content}`;
        this.props.doMerge(
          {
            merge_commit_message,
            merge_type: this.state.merge_type,
            should_remove_source_branch: formData.should_remove_source_branch,
          },

          () => {
            this.props.updatePageInfo(window.location.pathname, this.onClose);
          },
        );
      }
    });
  };

  renderDefaultTypeTag(i) {
    if (i !== 0) {
      return null;
    }

    return (
      <Tag size="small" type="primary" style={{ margin: '0 4px' }}>
        {intl.get({
          id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.DefaultType',
          defaultMessage: '默认类型',
        })}
      </Tag>
    );
  }

  getMergeTypeTitle = () => {
    const { merge_type } = this.state;
    let title = '';
    mrDataSource.forEach((item) => {
      if (item.key === merge_type) {
        title = item.title;
      }
    });
    return title;
  };

  render() {
    const { codeReviewDetail, mergeRequestType, isMerging, mr_ahead_behind_info } = this.props;
    const { support_merge_ff_only: supportMergeFFOnly } = mr_ahead_behind_info || {};
    const { target_branch } = codeReviewDetail;
    const { init } = this.field;
    const { merge_type } = this.state;
    // 选项顺序按 mergeRequestType 数组元素的顺序来
    const mergeTypes = mergeRequestType.map((item) =>
      mrDataSource.find((item2) => item2.key === item));

    const trigger = (
      <Balloon.Tooltip
        align="t"
        trigger={
          <Button type="primary" onClick={this.onDropdownClick}>
            {intl.get({
              id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Merge',
              defaultMessage: '合并',
            })}
          </Button>
        }
      >
        {intl.get({
          id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.MergeRequirementsMet',
          defaultMessage: '已达到合并要求',
        })}
      </Balloon.Tooltip>
    );

    // 如果只有一种合并方式,直接到弹窗内
    const isOneMergeType = mergeTypes && mergeTypes.length === 1;
    const onMergeTypeTrigger =
      mergeTypes[0] && mergeTypes[0].key === 'ff-only' && !supportMergeFFOnly ? (
        <Balloon.Tooltip
          align="t"
          trigger={
            <Button type="primary" disabled>
              {intl.get({
                id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Merge',
                defaultMessage: '合并',
              })}
            </Button>
          }
        >
          {intl.get({
            id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.TheMergeRequestCannotBe',
            defaultMessage: '目标分支上有提交，该合并请求不能使用 fast-forward 合并',
          })}
        </Balloon.Tooltip>
      ) : (
        trigger
      );

    const curTitle = this.getMergeTypeTitle();

    return (
      <React.Fragment>
        {isOneMergeType ? (
          <span
            style={{ display: 'inline-block', height: 32 }}
            onClick={() => {
              this.setState({
                isCommitMsgInputVisible: true,
                visible: true,
                merge_type: mergeRequestType[0],
              });

              this.commitMessage(mergeRequestType[0]);
            }}
          >
            {onMergeTypeTrigger}
          </span>
        ) : (
          <Dropdown
            trigger={<span style={{ display: 'inline-block', height: 32 }}>{trigger}</span>}
            triggerType="click"
            align="tr br"
            visible={this.state.dropdownVisible}
            onVisibleChange={(dropdownVisible, type) => {
              if (type === 'docClick') {
                this.setState({
                  dropdownVisible,
                });
              }
            }}
          >
            <Menu onItemClick={this.onOpen} className="merge-menu">
              {mergeTypes &&
                mergeTypes.map((item, i) => {
                  if (item.key === 'ff-only') {
                    return (
                      <Menu.Item
                        style={{ overflow: 'visible' }}
                        disabled={!supportMergeFFOnly}
                        key={item.key}
                      >
                        {supportMergeFFOnly ? (
                          <div className="merge-menu-item">
                            <div className="merge-menu-item-title">
                              {item.title}
                              {this.renderDefaultTypeTag(i)}
                            </div>
                            <div className="merge-menu-item-desc">{item.desc}</div>
                          </div>
                        ) : (
                          <Balloon.Tooltip
                            trigger={
                              <div className="merge-menu-item">
                                <div className="merge-menu-item-title">
                                  {item.title}
                                  {this.renderDefaultTypeTag(i)}
                                </div>
                                <div style={{ color: '#bfbfbf' }} className="merge-menu-item-desc">
                                  {item.desc}
                                </div>
                              </div>
                            }
                            align="b"
                          >
                            {intl.get({
                              id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.TheMergeRequestCannotBe',
                              defaultMessage:
                                '目标分支上有提交，该合并请求不能使用 fast-forward 合并',
                            })}
                          </Balloon.Tooltip>
                        )}
                      </Menu.Item>
                    );
                  } else {
                    return (
                      <Menu.Item key={item.key}>
                        <div className="merge-menu-item">
                          <div className="merge-menu-item-title">
                            {item.title}
                            {this.renderDefaultTypeTag(i)}
                          </div>
                          <div className="merge-menu-item-desc">{item.desc}</div>
                        </div>
                      </Menu.Item>
                    );
                  }
                })}
            </Menu>
          </Dropdown>
        )}

        {this.state.isCommitMsgInputVisible && (
          <Dialog
            title={
              <Tooltip
                trigger={
                  <div className="file-form-title">
                    {intl.get({
                      id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Submit',
                      defaultMessage: '提交到',
                    })}{' '}
                    {target_branch}
                  </div>
                }
                align="t"
              >
                <span style={{ wordBreak: 'break-all' }}>
                  {intl.get({
                    id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Submit',
                    defaultMessage: '提交到',
                  })}{' '}
                  {target_branch}
                </span>
              </Tooltip>
            }
            visible={this.state.visible}
            onOk={() => {
              this.onFormSave();
            }}
            onCancel={this.onClose}
            onClose={this.onClose}
            style={{ width: '600px' }}
            okProps={{
              children: intl.get({
                id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Submitted',
                defaultMessage: '提交',
              }),
              loading: isMerging,
            }}
            cancelProps={{
              children: intl.get({
                id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Cancel',
                defaultMessage: '取消',
              }),
            }}
            className="merge-dialog"
          >
            <Form
              labelAlign="top"
              direction="ver"
              field={this.field}
              className="commit-message-form"
            >
              {
                <Form.Item
                  label={intl.get({
                    id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.MergeMethod',
                    defaultMessage: '合并方式',
                  })}
                >
                  {curTitle}
                </Form.Item>
              }

              {/* rebase和fast-forward-only类型无需commit msg字段 */}
              {merge_type && merge_type !== 'rebase' && merge_type !== 'ff-only' && (
                <Form.Item
                  label={intl.get({
                    id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.Submitted',
                    defaultMessage: '提交',
                  })}
                >
                  <Input
                    {...init('merge_commit_message_title', {
                      initValue: `merge #${codeReviewDetail.id} into ${codeReviewDetail.target_branch} from ${codeReviewDetail.source_branch}`,
                      rules: [
                        {
                          required: true,
                          message: intl.get({
                            id: 'code-assets.src.utils.locale.ThisParameterIsRequired',
                            defaultMessage: '该项为必填项',
                          }),
                        },
                      ],
                    })}
                  />
                </Form.Item>
              )}

              {merge_type && merge_type !== 'rebase' && merge_type !== 'ff-only' && (
                <Form.Item
                  label={intl.get({
                    id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.SubmissionInformation',
                    defaultMessage: '提交信息',
                  })}
                >
                  <Input.TextArea {...init('merge_commit_message_content')} />
                </Form.Item>
              )}

              <Form.Item label="">
                <Checkbox
                  {...init('should_remove_source_branch', {
                    initValue: false,
                  })}
                >
                  {intl.get({
                    id: 'code-assets.components.mrTitleInfo.doMergeAndDialog.AutomaticallyDeleteSourceBranchesAfter',
                    defaultMessage: '合并后自动删除源分支',
                  })}
                </Checkbox>
              </Form.Item>
            </Form>
          </Dialog>
        )}
      </React.Fragment>
    );
  }
}
